package com.loyal.mwm.ui

import android.content.Intent
import android.text.TextUtils
import com.loyal.client.impl.RxSubscriberListener
import com.base.kit.GsonUtil
import com.loyal.rx3.RxUtil
import com.loyal.mwm.R
import com.loyal.mwm.base.BaseSwipeActivity
import com.loyal.mwm.beans.ResultBean
import com.loyal.mwm.databinding.ActivityAccountBinding
import com.loyal.mwm.handler.AccountSafetyHandler
import com.loyal.mwm.libs.rxjava.RxProgressSubscriber
import com.loyal.mwm.util.ImageUtil

class AccountSafetyActivity : BaseSwipeActivity<ActivityAccountBinding>(),
    RxSubscriberListener<String?> {
    override fun actLayoutRes(): Int {
        return R.layout.activity_account
    }

    override fun afterOnCreate() {
        val toolbar = binding.toolbar.root
        toolbar.title = "账号与安全"
        setSupportActionBar(toolbar)
        binding.click = AccountSafetyHandler(this, binding)
        binding.drawable = ImageUtil.getBackground(this)
        checkLocked()
    }

    override fun setEdgePosition(): Int {
        return LEFT
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        setResult(resultCode, data)
        finish()
    }

    private fun checkLocked() {
        val account: String = username
        val subscriber: RxProgressSubscriber<String> =
            RxProgressSubscriber<String>(this)
        subscriber.setDialogMessage("加载中...").showProgressDialog(true)
        subscriber.setSubscribeListener(this)
        RxUtil.rxExecute(subscriber.accountLock(account), subscriber)
    }

    override fun onResult(what: Int, tag: Any?, result: String?) {
        val resultBean = GsonUtil.json2Bean(result, ResultBean::class.java)
        if (resultBean != null) {
            if (TextUtils.equals("1", resultBean.code)) {
                toggleLocked(TextUtils.equals("1", replaceText(resultBean.message)))
            } else showToast(resultBean.message)
        } else showToast("解析设备锁信息失败")
    }

    private fun toggleLocked(locked: Boolean) {
        if (locked) {
            binding.accountDeviceLock.contentDescription = getString(R.string.on)
            binding.accountDeviceLock.setImageResource(R.mipmap.switch_on)
        } else {
            binding.accountDeviceLock.setImageResource(R.mipmap.switch_off)
            binding.accountDeviceLock.contentDescription = getString(R.string.off)
        }
    }

    override fun onError(what: Int, tag: Any?, e: Throwable?) {
        showErrorDialog("失败", e)
    }
}